package com.venus.mq.zk;

import com.venus.mq.model.RegisterBean;
import org.I0Itec.zkclient.ZkClient;

/**
 * Created by mc on 18/11/21.
 */
public class MqRegisterBean implements MqRegister {

    private ZkService zkService;

    public MqRegisterBean(ZkService zkService) {
        this.zkService = zkService;
    }

    private static final String rootNode = "/venus-mq";// 全路径示例:/venus-mq/topic/producer/address

    @Override
    public Boolean register(RegisterBean registerBean) {
        /**
         * 注册逻辑：
         * 1.查看根路径是否存在，不存在就创建根路径
         * 2.查看topic节点是否存在，不存在就创建
         * 3.查看注册对象是produce还是consumer，查看节点是否存在，不存在创建新的节点
         * 4.查看address节点是否存在，不存在创建新的节点
         */
        if(registerBean == null){
            return false;
        }
        Boolean rootResult = zkService.isExist(rootNode);
        if(!rootResult){
            zkService.createPerNode(rootNode);
        }

        Boolean topicResult = zkService.isExist(rootNode+"/"+registerBean.getTopicName());
        if(!topicResult){
            zkService.createPerNode(rootNode+"/"+registerBean.getTopicName());
        }

        Boolean clientResult = zkService.isExist(rootNode+"/"+registerBean.getTopicName()+"/"+registerBean.getProduceOrConsumer());
        if(!clientResult){
            zkService.createPerNode(rootNode+"/"+registerBean.getTopicName()+"/"+registerBean.getProduceOrConsumer());
        }

        Boolean addressResult = zkService.isExist(rootNode+"/"+registerBean.getTopicName()+"/"+registerBean.getProduceOrConsumer()+"/"+registerBean.getAddress());
        if(!addressResult){
            zkService.createPerNode(rootNode+"/"+registerBean.getTopicName()+"/"+registerBean.getProduceOrConsumer()+"/"+registerBean.getAddress());
        }
        return true;
    }


    public static void main(String[] args) {

        RegisterBean registerBean = new RegisterBean();
        registerBean.setAddress("127.0.0.1:2587");
        registerBean.setProduceOrConsumer("producer");
        registerBean.setTopicName("testTopic");
        ZkClient zkClient = ZkConfig.getInstance();
        new MqRegisterBean(new ZkServiceImpl(zkClient)).register(registerBean);


    }
}
